"""
Copyright (c) 2024 - present SKbioinfo
"""
from flask_restful import Resource
from flask import request,jsonify
from apps.API.connector.db_common import *
from apps.API.common.common_time import *
from apps.API.utils.log_helper import lg
from flask_jwt_extended import jwt_required
import datetime as dt

class interfaceRecentAnaCharts(Resource):
    def __init__(self):
            pass
    def _define_month(self):
        current_time = dt.datetime.today()
        day=0
        if current_time.month == 2:
            if int(current_time.year)%4 == 0:
                day=29
            else:
                day=28
        elif current_time.month in [1,3,5,7,8,10,12]:
            day=31
        elif current_time.month in [4,6,9,11]:
            day=30
        month_time='''{year}-{month}-{day}'''.format(
            year=current_time.year,
            month=current_time.month,
            day=day
        )
        return month_time

    def _three_months_interval_group_query(self,short_name:str,time_col:str,table_name:str,group_col:str,month_time:str):
        search_sql = ""
        ### SQL: month intervals search sql ###
        search_sql = f'''
            SELECT {group_col},SUM(CASE WHEN {short_name}.{time_col} BETWEEN DATE_SUB(\"{month_time}\", INTERVAL '30' DAY) AND \"{month_time}\" 
            THEN 1 ELSE 0  END) AS "1",
            SUM(CASE WHEN {short_name}.{time_col} BETWEEN  DATE_SUB(\"{month_time}\", INTERVAL '60' DAY) AND DATE_SUB(\"{month_time}\", INTERVAL '30' DAY) 
            THEN 1 ELSE 0  END) AS "2",
            SUM(CASE WHEN {short_name}.{time_col} BETWEEN  DATE_SUB(\"{month_time}\", INTERVAL '90' DAY) AND DATE_SUB(\"{month_time}\", INTERVAL '60' DAY) 
            THEN 1 ELSE 0  END) AS "3"
            FROM {table_name} as {short_name} GROUP BY {group_col}
        '''
        return search_sql
   
    @jwt_required()
    def get(self):
        try:
            month_time = self._define_month()
            querySQL=self._three_months_interval_group_query(
                short_name='ana',
                table_name='analysis',
                time_col='run_create_time',
                group_col='type',
                month_time=month_time
            )
            query_info=dic_query_info(querySQL)
            response=jsonify(query_info)
            response.status=202
            return response
        except Exception as e:
            lg.error(e)